import Lazyimg from "./Lazyimg";

export default class Lazyload {
    constructor(options) {
        this.options = options
        this.isAddListener = false
        this.lazyImgPool = []
    }

    bindlazy = (el, bindings) => {
        const parent = findParent(el)

        if(!this.isAddListener) {
            this.isAddListener = true
            parent.addEventListener(
                'scroll',
                this.handleScroll.bind(this)
                , false)
        }

        let lazyImg = new Lazyimg(
            el,
            bindings.value,
            this.options,
            this.imgRender,
        )
        this.lazyImgPool.push(lazyImg)
        this.handleScroll()
    }

    handleScroll = () => {
        let isVisible = false

        this.lazyImgPool.forEach((lazyImg) => {
            if(!lazyImg.loaded) {
                isVisible = lazyImg.checkIsVisible()
                isVisible && lazyImg.loadImg()
            }
        })
    }

    imgRender = (lazyImg, state) => {
        console.log(state)
        switch (state) {
            case 'loading':
                lazyImg.el.setAttribute('src', lazyImg.options.loading)
                break
            case 'error':
                lazyImg.el.setAttribute('src', lazyImg.options.error)
                break
            default:
                lazyImg.el.setAttribute('src', lazyImg.src)
                break
        }
    }
}

const findParent = (el) => {
    let parent = el.parentNode

    while(getComputedStyle(parent)['overflow'] !== 'auto' && getComputedStyle(parent)['overflow'] !== 'scroll') {
        parent = parent.parentNode
        if(parent.toString() === "[object HTMLDocument]") {
            break
        }
    }
    return parent
}